import { defineStore } from 'pinia'
import { getTeacherRoute, getStudentRoute } from '@/api/user'

/**
 * 路由状态管理
 * 实现路由的持久化存储，避免重复加载
 */
export const useRouteStore = defineStore('route', {
  state: () => ({
    teacherRoutes: JSON.parse(localStorage.getItem('teacherRoutes')) || null, // 教师路由
    studentRoutes: JSON.parse(localStorage.getItem('studentRoutes')) || null, // 学生路由
    hasLoaded: false, // 标记是否已加载过路由
  }),

  getters: {
    // 获取教师菜单
    teacherMenus: (state) => {
      if (!state.teacherRoutes || !state.teacherRoutes.children) {
        return []
      }

      // 返回子路由作为菜单项
      return state.teacherRoutes.children
        .filter((item) => item.meta?.isShow !== false)
        .map((item) => ({
          ...item,
          path: item.meta?.path || `/teacher/${item.path}`,
          // 如果有子路由，也处理子路由的路径
          children: item.children
            ? item.children
                .filter((child) => child.meta?.isShow !== false)
                .map((child) => ({
                  ...child,
                  path:
                    child.meta?.path || `/teacher/${item.path}/${child.path}`,
                }))
            : [],
        }))
    },

    // 获取学生菜单
    studentMenus: (state) => {
      if (!state.studentRoutes || !state.studentRoutes.children) {
        return []
      }

      // 返回子路由作为菜单项
      return state.studentRoutes.children
        .filter((item) => item.meta?.isShow !== false)
        .map((item) => ({
          ...item,
          path: item.meta?.path || `/student/${item.path}`,
          // 如果有子路由，也处理子路由的路径
          children: item.children
            ? item.children
                .filter((child) => child.meta?.isShow !== false)
                .map((child) => ({
                  ...child,
                  path:
                    child.meta?.path || `/student/${item.path}/${child.path}`,
                }))
            : [],
        }))
    },
  },

  actions: {
    // 加载教师路由
    async loadTeacherRoutes() {
      if (this.teacherRoutes) {
        console.log('使用缓存的教师路由')
        return this.teacherRoutes
      }

      try {
        console.log('从API获取教师路由')
        const routes = await getTeacherRoute()
        this.teacherRoutes = routes
        // 持久化存储路由
        localStorage.setItem('teacherRoutes', JSON.stringify(routes))
        return routes
      } catch (error) {
        console.error('加载教师路由失败:', error)
        return null
      }
    },

    // 加载学生路由
    async loadStudentRoutes() {
      if (this.studentRoutes) {
        console.log('使用缓存的学生路由')
        return this.studentRoutes
      }

      try {
        console.log('从API获取学生路由')
        const routes = await getStudentRoute()
        this.studentRoutes = routes
        // 持久化存储路由
        localStorage.setItem('studentRoutes', JSON.stringify(routes))
        return routes
      } catch (error) {
        console.error('加载学生路由失败:', error)
        return null
      }
    },

    // 根据角色加载路由
    async loadRoutesByRole(role) {
      if (role === 'teacher') {
        return this.loadTeacherRoutes()
      } else {
        return this.loadStudentRoutes()
      }
    },

    // 设置路由加载状态
    setLoaded(status) {
      this.hasLoaded = status
    },

    // 清除路由缓存
    clearRoutes() {
      this.teacherRoutes = null
      this.studentRoutes = null
      this.hasLoaded = false
      // 清除本地存储
      localStorage.removeItem('teacherRoutes')
      localStorage.removeItem('studentRoutes')
    },
  },
})
